package whf.framework.workflow.assign.parser;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.jdom.Element;

import whf.framework.exception.AppException;
import whf.framework.security.entity.User;
import whf.framework.util.Utils;

/**
 * @author king
 *
 */
@SuppressWarnings("unchecked")
public abstract class DefaultAssignmentParser implements AssignmentParser {
	protected Element source;
	
	protected Set<User> users = Utils.newHashSet();
	
	public void setSource(Element source) throws AppException {
		this.source = source;
		this.parseSourceElement(source);
	}
	
	protected String getAttribute(String attributeName) {
		return source.getAttributeValue(attributeName);
	}
	
	protected String getText() {
		return source.getText();
	}
	
	protected List<Element> getChildrenElements() {
		return source.getChildren();
	}
	
	public Set<AssignmentParser> getChildrenParsers() {
		Set<AssignmentParser> childrenParsers = new HashSet<AssignmentParser>();
		List<Element> childrenElements = this.getChildrenElements();
		String role = null;
		Collection<String>depts = null;
		if(this instanceof RoleableAssignmentParser) {
			role = ((RoleableAssignmentParser)this).getRoleName();
		}
		if(this instanceof DeptableAssignmentParser) {
			depts = ((DeptableAssignmentParser)this).getDeptCodes();
		}
		for(Element ele: childrenElements) {
			AssignmentParser parser = AssignmentParserFactory.getAssignmentParser(ele, role, depts);
			if(parser != null)
				childrenParsers.add(parser);
		}
		return childrenParsers;
	}
	
	protected abstract void parseSourceElement(Element source) throws AppException;
}
